<?
if (preg_match("#" . basename(__FILE__) . "#", $_SERVER['PHP_SELF'])) {
	die('This page cannot be called directly.') ;
}
class ajax_image {
	function playme(){
        $code = Url::getParam('code');
        //yêu cầu đặt tên $code=tên của method trong class
        if (method_exists($this, $code)) {
            $this->$code();
        }else{
            $this->home();
        }
	}
	
	function home(){
		global $display;
		die("Nothing to do...");
	}
	
	function add_image()
	{
		if(User::is_login() && User::have_permit(array("hotel_add", "room_add")))
		{
            require_once 'includes/qqUploadedFile.php';
            
            // list of valid extensions, ex. array("jpeg", "xml", "bmp")
            $allowedExtensions = array("jpeg","png","jpg","gif");

            // max file size in bytes
            $sizeLimit = 5 * 1024 * 1024;

            $path = ROOT_PATH.'images/user/' . User::id() . '/';
            ECLib::CheckDir($path);

            $uploader 	= new qqFileUploader($allowedExtensions, $sizeLimit);
            
            $result 	= $uploader->handleUpload($path);

            if(isset($result["error"]))
            {
                echo json_encode(
				                    array(
				                        'type'		=>	0,
				                        'error'		=>	true,
				                        'message'	=>	$result["error"]
				                    )
				                );
            }
            else
            {
                $data['img_url'] = 'images/user/' . User::id() . '/' .$result["filename"];
                $data['img_server'] = 0;
                
                echo json_encode(
				                    array(
				                        'type'		=>	0,
				                        'success'	=>	true,
				                        'source'	=>	$data['img_server'],
				                        'fullpath'	=>	$data['img_url'],
				                        'filename'	=>	$result["filename"]
				                    )
				                );
            }
        }
        else
        {
            echo json_encode(
				                array(
				                    'type'		=>	0,
				                    'error'		=>	true,
				                    'message'	=>	'Bạn không có quyền upload file.'
				                )
				            );
        }
	}

    function del_new_image(){
        if(User::is_login() && User::have_permit(array("hotel_add", "room_add")))
		{
            $image_id= Url::get("id");
            $image_id = str_replace('_','.',$image_id);

            $imageDel = ROOT_PATH.'images/user/' . User::id() . '/' . $image_id;
            if (unlink($imageDel)){
                echo json_encode(
                                array(
                                    'type'		=>	0,
                                    'success'		=>	true,
                                    'message'	=>	'Xóa thành công.'
                                )
                            );
            } else {
                echo json_encode(
                                    array(
                                        'type'		=>	0,
                                        'error'		=>	true,
                                        'message'	=>	'Bạn không có quyền xóa file.'
                                    )
                                );
            }
        }
    }

    function save_image() 
    {
        $id	=	Url::getInt('img_id', 0);

        if(User::is_login() && $image = Db_Image::have_permit(array("hotel_add", "room_add"), $id))
        {
            if($id && ($image!==true || ($image = DB::exists_id('images', $id, __FILE__ . ' line ' . __LINE__))))
            {
                $data['img_name'] 	= HTML::clean_value(Url::get('img_name'));
                
                $pathinfo 			= pathinfo($image['img_url']);
                
                //$fileName 		= String::safe_title($data['img_name']).'-'.$image['id'].'.'.$pathinfo['extension'];
                $fileName 			= String::safe_title($data['img_name']) . ".{$pathinfo['extension']}";
                
                if($image['img_server'])//Chưa upload lên storage
                {
                    if (Upload::storage_rename_file($image['img_url'], $fileName, $image['img_server']))
                    {
                        //$data['img_url'] = substr($image['img_url'], 0, (strrpos($image['img_url'], '/') + 1) ) . $fileName;
                        
                        $data['img_url'] = dirname($image['img_url']) . "/$fileName";
                    }
                } 
                else
                {
                	//TuanNK edit 2012.09.07
                    //$up_folder = UP_FOLDER . "/" . date("Y/m/d/", TIME_NOW).round($image['user_id'] / 1000).'/'.$image['user_id'].'/';
                    $up_folder = Upload::folderUpload($image['user_id']) . "{$image['id']}/";

                    if(Upload::storage_check_dir($up_folder, true, IMAGE_SERVER_NO)) 
                    {
                        $local_file 		= 	ROOT_PATH	.	$image['img_url'];
                        $destination_file 	= 	$up_folder 	. 	$fileName;

                        if (Upload::storage_put_file($destination_file, $local_file, IMAGE_SERVER_NO))
                        {
                            unlink($local_file);
                            
                            $data['img_url'] 	= $destination_file;
                            $data['img_server'] = IMAGE_SERVER_NO;
                        }
                    }
                }
                
                if(!$image['img_server'])
                {
                    //$fileName = substr($image['img_url'], 0, strrpos($image['img_url'], '/')+1).$fileName;
                    $fileName = dirname($image['img_url']) . "/$fileName";;
                    
                    if(rename(ROOT_PATH . $image['img_url'], ROOT_PATH . $fileName))
                    {
                        $data['img_url'] = $fileName;
                    }
                }
                
                if(Db_Image::update($data, $id)) 
                {
                    if(isset($data['img_url'])) 
                    {
                    	$image['img_url'] = $data['img_url'];
                    }
                    
                    if(isset($data['img_server'])) 
                    {
                    	$image['img_server'] = $data['img_server'];
                    }
                    
                    echo json_encode(
				                        array(
				                            'type'		=>	0,
				                            'success'	=>	true,
				                            'img_url'	=>	$image['img_url'],
				                            'img_server'=>	$image['img_server'],
				                        )
				                    );
                }
                else
                {
                    echo 'unsuccess';
                }
            }
            else
            {
                echo 'not_found';
            }
        }
        else
        {
            echo 'no_perm';
        }
    }
}
?>